package problem56;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//56.合并区间
//https://leetcode.cn/problems/merge-intervals/

class Solution {
    public int[][] merge(int[][] intervals) {
        List<int[]> list = new ArrayList<>();
        Arrays.sort(intervals, (a, b)->a[0]-b[0]);
        int n = intervals.length;
        int l = intervals[0][0], r = intervals[0][1];
        for(int i = 1; i<n; i++) {
            if(intervals[i][0] <= r) {
                r = Math.max(intervals[i][1], r);
            }else {
                list.add(new int[]{l, r});
                l = intervals[i][0];
                r = intervals[i][1];
            }
        }
        list.add(new int[]{l, r});
        return list.toArray(new int[list.size()][2]);
    }
}